// detail.js
// 导入请求工具
const { get, post } = require('../../utils/request');
const app = getApp();

Page({
  data: {
    goods: {}, // 商品详情数据
    reviews: [], // 用户评价
    reviewsCount: 0, // 评价总数
    recommendations: [], // 推荐商品
    specifications: [], // 商品规格
    selectedSpecs: {}, // 已选规格
    selectedSpec: '请选择规格', // 已选规格文本显示
    quantity: 1, // 购买数量
    showSpecModal: false, // 是否显示规格选择弹窗
    cartCount: 0 // 购物车数量
  },

  onLoad: function(options) {
    // 获取商品ID
    this.goodsId = options.id;
    // 加载商品数据
    this.loadGoodsData();
  },

  onShow: function() {
    // 更新购物车数量
    this.setData({
      cartCount: app.globalData.cartCount || 0
    });
  },

  /**
   * 加载商品数据
   */
  loadGoodsData: function() {
    wx.showLoading({
      title: '加载中',
    });

    get(`/api/goods/${this.goodsId}`)
      .then(res => {
        wx.hideLoading();
        
        // 格式化商品数据
        const goods = res || {};
        // 初始化规格信息
        const specifications = goods.specifications || [];
        
        // 设置默认选中规格
        const selectedSpecs = {};
        specifications.forEach(spec => {
          if (spec.values && spec.values.length > 0) {
            selectedSpecs[spec.name] = spec.values[0];
          }
        });
        
        // 生成选中规格文本
        const selectedSpec = this.generateSelectedSpecText(selectedSpecs);
        
        // 模拟评价数据
        const reviews = this.generateMockReviews();
        const reviewsCount = reviews.length;
        
        // 模拟推荐商品
        const recommendations = this.generateMockRecommendations();
        
        this.setData({
          goods: goods,
          specifications: specifications,
          selectedSpecs: selectedSpecs,
          selectedSpec: selectedSpec,
          reviews: reviews,
          reviewsCount: reviewsCount,
          recommendations: recommendations
        });
      })
      .catch(err => {
        wx.hideLoading();
        console.error('加载商品数据失败', err);
        wx.showToast({
          title: '加载商品失败',
          icon: 'none'
        });
      });
  },

  /**
   * 生成选中规格文本
   */
  generateSelectedSpecText: function(selectedSpecs) {
    if (!selectedSpecs || Object.keys(selectedSpecs).length === 0) {
      return '请选择规格';
    }
    
    let text = '';
    Object.keys(selectedSpecs).forEach(key => {
      text += `${key}: ${selectedSpecs[key]} `;
    });
    
    return text.trim();
  },

  /**
   * 生成模拟评价数据
   */
  generateMockReviews: function() {
    return [
      {
        avatar: '/assets/images/avatar1.png',
        nickname: '张先生',
        rating: 5,
        content: '商品质量很好，配送也很快，很满意的一次购物体验！',
        images: ['/assets/images/review1.png', '/assets/images/review2.png'],
        create_time: '2023-10-15 15:30'
      },
      {
        avatar: '/assets/images/avatar2.png',
        nickname: '李女士',
        rating: 4,
        content: '商品和描述的一样，就是包装有点简陋，不过不影响使用，好评！',
        images: ['/assets/images/review3.png'],
        create_time: '2023-10-14 10:15'
      }
    ];
  },

  /**
   * 生成模拟推荐商品
   */
  generateMockRecommendations: function() {
    return [
      {
        id: 101,
        name: '新鲜水果拼盘',
        image: '/assets/images/fruit1.png',
        current_price: 19.9,
        original_price: 29.9,
        sales_volume: 1280
      },
      {
        id: 102,
        name: '有机蔬菜组合',
        image: '/assets/images/vegetable1.png',
        current_price: 24.9,
        original_price: 34.9,
        sales_volume: 960
      },
      {
        id: 103,
        name: '精选肉类套餐',
        image: '/assets/images/meat1.png',
        current_price: 49.9,
        original_price: 69.9,
        sales_volume: 780
      },
      {
        id: 104,
        name: '乳制品组合',
        image: '/assets/images/dairy1.png',
        current_price: 39.9,
        original_price: 59.9,
        sales_volume: 650
      }
    ];
  },

  /**
   * 显示规格选择弹窗
   */
  showSpecModal: function() {
    this.setData({
      showSpecModal: true,
      quantity: 1
    });
  },

  /**
   * 隐藏规格选择弹窗
   */
  hideSpecModal: function() {
    this.setData({
      showSpecModal: false
    });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation: function() {
    // 阻止事件冒泡
  },

  /**
   * 选择规格
   */
  selectSpec: function(e) {
    const specName = e.currentTarget.dataset.specName;
    const specValue = e.currentTarget.dataset.specValue;
    
    // 更新选中规格
    const selectedSpecs = {
      ...this.data.selectedSpecs,
      [specName]: specValue
    };
    
    // 生成选中规格文本
    const selectedSpec = this.generateSelectedSpecText(selectedSpecs);
    
    this.setData({
      selectedSpecs: selectedSpecs,
      selectedSpec: selectedSpec
    });
  },

  /**
   * 减少数量
   */
  decreaseQuantity: function() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
    }
  },

  /**
   * 增加数量
   */
  increaseQuantity: function() {
    if (this.data.quantity < this.data.goods.stock) {
      this.setData({
        quantity: this.data.quantity + 1
      });
    } else {
      wx.showToast({
        title: '已达到最大库存',
        icon: 'none'
      });
    }
  },

  /**
   * 确认加入购物车
   */
  confirmAddToCart: function() {
    const { goods, selectedSpecs, quantity } = this.data;
    
    // 显示加载中
    wx.showLoading({
      title: '加入购物车',
    });
    
    // 调用API加入购物车
    post('/api/cart/add/', {
      goods_id: goods.id,
      num: quantity,
      specs: selectedSpecs
    })
      .then(res => {
        wx.hideLoading();
        
        // 隐藏弹窗
        this.hideSpecModal();
        
        // 更新购物车数量
        const cartCount = (app.globalData.cartCount || 0) + quantity;
        app.globalData.cartCount = cartCount;
        app.updateCartCount();
        
        this.setData({
          cartCount: cartCount
        });
        
        wx.showToast({
          title: '加入购物车成功',
          icon: 'success'
        });
      })
      .catch(err => {
        wx.hideLoading();
        console.error('加入购物车失败', err);
        wx.showToast({
          title: '加入购物车失败',
          icon: 'none'
        });
      });
  },

  /**
   * 立即购买
   */
  buyNow: function() {
    // 先显示规格选择弹窗
    this.showSpecModal();
    
    // 设置一个标志，表示是立即购买
    this.isBuyNow = true;
  },

  /**
   * 打开购物车
   */
  openCart: function() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },

  /**
   * 查看全部评价
   */
  viewAllReviews: function() {
    wx.navigateTo({
      url: `/pages/goods/reviews?id=${this.goodsId}`
    });
  },

  /**
   * 查看推荐商品详情
   */
  viewRecommendation: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/goods/detail?id=${id}`
    });
  }
});